/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.vacoor.nothing.common.util.Throwables;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.vacoor.nothing.web.util.Images.toBuffered;

/**
 * QRCode.create("http://www.baidu.com", logo).toBufferedImage(200, 200)
 *
 * @author vacoor
 */
public class QRCode {
    private static int FRAME_WIDTH = 2;
    private static MultiFormatWriter mutiWriter = new MultiFormatWriter();  // 二维码写码器

    private final String content;
    private final BufferedImage logo;

    public static QRCode create(String content) {
        return create(content, null);
    }

    public static QRCode create(String content, BufferedImage logo) {
        return new QRCode(content, logo);
    }

    private QRCode(String content, BufferedImage logo) {
        this.content = content;
        this.logo = logo;
    }

    public BufferedImage toBufferedImage(final int w, final int h) {
        try {
            int logoW = 0;
            int logoH = 0;
            int[][] logoPixels = new int[0][0];

            if (null != logo) {
                logoW = w / 4;
                logoH = h / 4;
                BufferedImage logo = scale(this.logo, logoW, logoH, true);

                logoPixels = new int[logoW][logoH];
                for (int x = 0; x < logo.getWidth(); x++) {
                    for (int y = 0; y < logo.getHeight(); y++) {
                        logoPixels[x][y] = logo.getRGB(x, y);
                    }
                }
            }

            Map<EncodeHintType, Object> hits = new HashMap<EncodeHintType, Object>();
            hits.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hits.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            // 生成二维码矩阵
            BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE, w, h, hits);
            int halfW = matrix.getWidth() / 2;
            int halfH = matrix.getHeight() / 2;
            int logoHalfW = logoW / 2;
            int logoHalfH = logoH / 2;
            int[] pixels = new int[w * h];

            for (int y = 0; y < matrix.getHeight(); y++) {
                for (int x = 0; x < matrix.getWidth(); x++) {
                /*
                //左上角颜色,根据自己需要调整颜色范围和颜色
                if (x > 0 && x < 170 && y > 0 && y < 170) {
                    Color color = new Color(231, 144, 56);
                    int colorInt = color.getRGB();
                    pixels[y * width + x] = matrix.get(x, y) ? colorInt : 0xffffff;
                } else */
                    if (x > halfW - logoHalfW && x < halfW + logoHalfW && y > halfH - logoHalfH && y < halfH + logoHalfH) {
                        // 读取图片
                        pixels[y * w + x] = logoPixels[x - halfW + logoHalfW][y - halfH + logoHalfW];
                    } else if ((x > halfW - logoHalfW - FRAME_WIDTH && x < halfW - logoHalfW + FRAME_WIDTH && y > halfH - logoHalfH - FRAME_WIDTH && y < halfH + logoHalfH + FRAME_WIDTH) ||
                            (x > halfW + logoHalfW - FRAME_WIDTH && x < halfW + logoHalfW + FRAME_WIDTH && y > halfH - logoHalfH - FRAME_WIDTH && y < halfH + logoHalfH + FRAME_WIDTH) ||
                            (x > halfW - logoHalfW - FRAME_WIDTH && x < halfW + logoHalfW + FRAME_WIDTH && y > halfH - logoHalfH - FRAME_WIDTH && y < halfH - logoHalfH + FRAME_WIDTH) ||
                            (x > halfW - logoHalfW - FRAME_WIDTH && x < halfW + logoHalfW + FRAME_WIDTH && y > halfH + logoHalfH - FRAME_WIDTH && y < halfH + logoHalfH + FRAME_WIDTH)) {
                        // 在图片四周形成边框
                        pixels[y * w + x] = 0xfffffff;
                    } else {      //二维码颜色
                        /*
                        int r = (int) (50 - (50.0 - 13.0) / matrix.getHeight() * (y + 1));
                        int g = (int) (165 - (165.0 - 72.0) / matrix.getHeight() * (y + 1));
                        int b = (int) (162 - (162.0 - 107.0) / matrix.getHeight() * (y + 1));
                        Color color = new Color(r, g, b);
                        */
                        Color color = Color.BLACK;
                        int rgb = color.getRGB();      // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                        pixels[y * w + x] = matrix.get(x, y) ? rgb : 0xffffff;//0x000000:0xffffff
                    }
                }
            }

            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            image.getRaster().setDataElements(0, 0, w, h, pixels);
            return image;
        } catch (Exception e) {
            throw Throwables.unchecked(e);
        }
    }

    /**
     * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标
     *
     * @param img       源文件
     * @param height    目标高度
     * @param width     目标宽度
     * @param hasFiller 比例不对时是否需要补白：true为补白; false为不补白;
     * @throws java.io.IOException
     */
    private static BufferedImage scale(BufferedImage img, int height, int width, boolean hasFiller) throws IOException {
        double ratio; // 缩放比例
        Image destImage = img.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);   // 计算比例
        if ((img.getHeight() > height) || (img.getWidth() > width)) {
            if (img.getHeight() > img.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / img.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / img.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(img, null);
        }

        if (hasFiller) {// 补白
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = image.createGraphics();


            g2d.setColor(Color.white);
            g2d.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null)) {
                g2d.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);
            } else {
                g2d.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);
            }
            g2d.dispose();
            destImage = image;
        }
        return toBuffered(destImage);
    }

    public static void main(String[] args) {
        BufferedImage img = QRCode.create("http://vacoor.github.io").toBufferedImage(200, 200);
        JOptionPane.showMessageDialog(null, null, "title", JOptionPane.YES_OPTION, new ImageIcon(img));
    }
}

